package com.googlecode.afdbaccess.web.common.servletfilter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class CdnETagFilter implements Filter {
    //private final static Logger log = Logger.getLogger(CdnETagFilter.class);

    private static final String ETAG_VALUE = "\"static\"";

    class ResponseWrapper extends HttpServletResponseWrapper {
        public ResponseWrapper(HttpServletResponse response) {
            super(response);
        }

        @Override
        public void setHeader(String name, String value) {
            if(name.equals("ETag") || name.equals("Last-Modified")) {
                // do nothing. Swallow the header
                return;
            }

            super.setHeader(name, value);
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //log.info("CdnETagFilter.doFilter: " + ((HttpServletRequest)req).getRequestURI());

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse)res;

        if(request.getHeader("If-None-Match") != null && request.getHeader("If-None-Match").equals(ETAG_VALUE)) {
            ETagFilter.clearUnneededHeaders(response);
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            if(response.isCommitted()) {
                throw new RuntimeException("isCommitted() == true BEFORE");
            }
            
            response.setHeader("ETag", ETAG_VALUE);

            chain.doFilter(req, new ResponseWrapper(response));
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // do nothing
    }

    @Override
    public void destroy() {
        // do nothing
    }

}